package cn.xshi.bpm.common.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.xshi.bpm.util.message.vo.MessageDTO;
import cn.xshi.common.util.SpringUtils;
import cn.xshi.bpm.common.listener.worker.MessageWorker;
import cn.xshi.bpm.util.ActivitiUtil;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * @Desc 边界事件超时ServiceTask（服务任务）监听器
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
@Slf4j
public class TimeoutServiceTaskListener implements JavaDelegate {

    @Override
    public void execute(DelegateExecution execution) {
        // 触发了定时器。job包含在事件中。
        doMessage(execution);
    }

    /**
     *
     * @param execution
     */
    private void doMessage(DelegateExecution execution){
        log.info("-----启动定时事件-------");

        String processInstanceId = execution.getProcessInstanceId();//获取流程实例id
        ActivitiUtil activitiUtil = SpringUtils.getBean(ActivitiUtil.class);
        List<Task> taskList = activitiUtil.getTaskListByProcessInstanceId(processInstanceId);//获取活动中任务

        if(!CollectionUtil.isEmpty(taskList)){
            for(Task task: taskList){
                String nodeId = task.getTaskDefinitionKey();//节点编号

                String assigne = task.getAssignee();//获取办理人

                String businessKey = activitiUtil.getBusinessKey(task.getId());//获取业务Key

                String owner = task.getOwner();//获取任务所属者

                List<IdentityLink> candidators = activitiUtil.getCandidatorObjects(task.getId());//候选人或组

                sendMessage(task.getId(),nodeId,assigne,businessKey,owner,candidators);
            }
        }
    }

    /**
     * 发送消息中间件
     * @param taskId
     * @param nodeId
     * @param assigne
     * @param businessKey
     * @param owner
     * @param candidators
     */
    private void sendMessage(String taskId,String nodeId,String assigne,String businessKey,String owner,List<IdentityLink> candidators){
        Runnable runnable = new MessageWorker(new MessageDTO(taskId, nodeId, assigne, businessKey, owner,candidators));
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
